#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    :CardLoader.py
@Author  :keyin
@Time    :2021-02-19 12:33
"""
import os
from datetime import datetime
from os.path import join

from PyQt5.QtCore import QThread, pyqtSignal
from PyQt5.QtWidgets import QTableWidgetItem, QFileDialog, QLineEdit, QMessageBox

import setings
from apps.card import views
from apps.card.views import CardDataView

# BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
from utils.genJsonResponse import json_response

BASE_DIR = setings.BASE_DIR


class myThread(QThread):
    trigger = pyqtSignal(object)  # 自定义一个信号，object是要返回给回调函数的返回值的Type

    def __init__(self, imgName, face):
        super(myThread, self).__init__()
        self.imgName = imgName
        self.face = face

    def run(self):
        # aip = CardAip(self.imgName)
        # card = aip.getinfo(self.face)
        data = CardDataView.get_card_info(self.face, self.imgName)
        print(data)
        self.trigger.emit(data)


class Loader:
    def __init__(self, frame, signals):
        self.frame = frame
        self.signals = signals

    def load(self):
        pass

    def check_name(self):
        if self.frame.txt_name.text() != '':
            print(self.frame.txt_name.isEnabled())
            if self.frame.txt_name.isEnabled():
                self.frame.btn_base_Edit.setEnabled(0)
                self.frame.btn_base_Del.setEnabled(0)
            else:
                self.frame.btn_base_Edit.setEnabled(1)
                self.frame.btn_base_Del.setEnabled(1)
        else:
            self.frame.btn_base_Edit.setEnabled(0)
            self.frame.btn_base_Del.setEnabled(0)


# 初始显示得到内容
class CardLoader(Loader):

    def load(self):
        self.load_tableWidget()

    def load_tableWidget(self):
        """
        加载当前前15个数据到tableWidget
        :return:
        """
        view = CardDataView()
        res = view.get_select(0, 15)
        # print('res======', res)
        print(res['data']['res'])
        # self.frame.card_tableWidget.setRowCount(0)
        self.frame.card_tableWidget.clearContents()

        if res['data']:
            res = res['data']['res']
            # print("DATA:-----", res)

            x = 0
            for i in res:
                y = 0
                for row in i:
                    # print(row)
                    newStr = str(row)
                    newItem = QTableWidgetItem(newStr)
                    self.frame.card_tableWidget.setItem(x, y, newItem)
                    y = y + 1
                x = x + 1
        self.check_name()


# 点击tableWidget时显示详细信息
class DetailLoader(Loader):

    def load(self):
        # print("="*10, len(self.frame.card_tableWidget.selectedItems()))
        print("=" * 10)
        if len(self.frame.card_tableWidget.selectedItems()) != 0:
            idNumber = str(self.frame.card_tableWidget.selectedItems()[2].text())
            print(idNumber)
            view = CardDataView()
            res = view.get_idNumber(idNumber)
            res = res['data']['res']
            # res = CardData()
            # self.frame = Ui_card
            # print('='*40)
            # print(res.c_valStart)
            # print(res.c_valEnd)
            self.frame.txt_name.setText(res.c_name)
            self.frame.txt_sex.setText(res.c_sex)
            self.frame.txt_nation.setText(res.c_nation)
            self.frame.txt_address.setText(res.c_address)
            self.frame.txt_id_numer.setText(res.c_idNumber)
            self.frame.txt_start.setText(str(res.c_valStart))
            self.frame.txt_end.setText(str(res.c_valEnd))
            self.frame.txt_Phone.setText(res.c_mobile)
            self.frame.txt_check.setText(res.c_checkPhone)
            self.frame.txt_wechat.setText(res.c_wechat)

            self.frame.comEB.setCurrentIndex(res.c_em)

            self.check_name()


# 点击pushButton
class CardCuidLoader(Loader):
    imgName=''

    def btn_change_ui(self, enabled_str):
        enabled_list = [int(x) for x in enabled_str]
        for i in self.frame.findChildren(QLineEdit):
            i.setEnabled(enabled_list[9])
        self.frame.btn_base_New.setEnabled(enabled_list[0])
        self.frame.btn_base_Edit.setEnabled(enabled_list[1])
        self.frame.btn_base_Save.setEnabled(enabled_list[2])
        self.frame.btn_base_Del.setEnabled(enabled_list[3])
        self.frame.btn_base_Cancel.setEnabled(enabled_list[4])
        self.frame.lbl_Front.setEnabled(enabled_list[5])
        self.frame.lbl_Back.setEnabled(enabled_list[6])
        self.frame.card_tableWidget.setEnabled(enabled_list[7])
        self.frame.comEB.setEnabled(enabled_list[8])

    def load(self):
        # print(type(self.frame.sender()))
        # 获取信号发送者的objectName
        objectName = self.frame.sender().objectName()
        print(objectName)


        if objectName == 'btn_base_New':
            self.btn_change_ui('0010111011')
            for i in self.frame.findChildren(QLineEdit):
                i.setText('')
            self.frame.comEB.setCurrentIndex(-1)
            print('btn_base_new被点击')

        if objectName == 'btn_base_Save':
            self.btn_change_ui('1101000100')
            print('保存按钮被点击')
            print('=========', self.frame.txt_name.text())
            if len(self.frame.txt_name.text()) != 0:
                dl = CardLoader(self.frame, signals=None)
                data = {'c_name': self.frame.txt_name.text(),
                        'c_sex': self.frame.txt_sex.text(),
                        'c_nation': self.frame.txt_nation.text(),
                        'c_idNumber': self.frame.txt_id_numer.text(),
                        'c_address': self.frame.txt_address.text(),
                        'c_valStart': self.frame.txt_start.text(),
                        'c_valEnd': self.frame.txt_end.text(),

                        'c_mobile': self.frame.txt_Phone.text(),
                        'c_checkPhone': self.frame.txt_check.text(),
                        'c_wechat': self.frame.txt_wechat.text(),
                        'c_em': self.frame.comEB.currentIndex(),
                       }

                data = json_response(data=data)
                view = CardDataView()
                # res = view.save(data)
                if view.save(data)['errno'] == '4003':
                    # reply = QMessageBox.question(self.frame, '提示', res['errmsg'],QMessageBox.Ok|QMessageBox.Close, QMessageBox.Close )
                    if QMessageBox.question(self.frame, '提示', view.save(data)['errmsg'],
                                            QMessageBox.Ok|QMessageBox.Close,
                                            QMessageBox.Close ) == QMessageBox.Ok:
                        view.updata(data=data)
                        dl.load_tableWidget()
                    else:
                        return

                dl.load_tableWidget()




        if objectName == 'btn_base_Edit':
            self.btn_change_ui('0010111011')
            print('修改按钮被点击')


        if objectName == 'btn_base_Del':
            self.btn_change_ui('1000000100')
            print('删除按钮被点击')
            id_number = self.frame.txt_id_numer.text()
            view = CardDataView()
            view.deltele_idNumber(id_number)
            dl = CardLoader(self.frame, signals=None)
            dl.load_tableWidget()

        if objectName == 'btn_base_Cancel':
            self.btn_change_ui('1101000100')
            print('取消按钮被点击')
            self.frame.comEB.setCurrentIndex(-1)

        if objectName == 'lbl_Front':
            face = 'Front'
            self.imgName, _ = QFileDialog.getOpenFileName(filter='*.jpg;*.png')
            if self.imgName:
                self.mbt = myThread(self.imgName, face)  # 定义线程，self.imgName和face是参数
                self.mbt.trigger.connect(self.set_txt_fv)  # 定义线程结束后执行那个函数，参数是信号发送emit后的值
                self.mbt.start()

        if objectName == 'lbl_Back':
            face = 'Back'
            self.imgName, _ = QFileDialog.getOpenFileName(filter='*.jpg;*.png')
            if self.imgName:
                self.mbt = myThread(self.imgName, face)  # 定义线程，self.imgName和face是参数
                self.mbt.trigger.connect(self.set_txt_bv)  # 定义线程结束后执行那个函数，参数是信号发送emit后的值
                self.mbt.start()

        self.check_name()

    def set_txt_fv(self, data):
        data = data['data']
        if data:
            self.frame.txt_name.setText(data['姓名']['words']),
            self.frame.txt_sex.setText(data['性别']['words']),
            self.frame.txt_nation.setText(data['民族']['words']),
            self.frame.txt_address.setText(data['住址']['words']),
            self.frame.txt_id_numer.setText(data['公民身份号码']['words']),

    def set_txt_bv(self, data):
        data = data['data']
        self.frame.txt_start.setText(data['签发日期']['words'])
        self.frame.txt_end.setText(data['失效日期']['words'])


if __name__ == '__main__':
    face = 'Back'
    path = join(BASE_DIR, 'apps', 'card', '4.jpg')
    print(path)
    # imgfile, _ = QFileDialog.getOpenFileName(filter='*.jpg;*.png')
    data = CardDataView.get_card_info(face, path)
    print(data['data'])
    print(data['data'].keys())
